﻿Imports WiremetModel.Entities.SupplyOrders
Imports GMap.NET
Imports GMap.NET.WindowsForms

Public Class SupplierView

    Private _unitOfWork As UnitOfWork
    Private _supplierDictionary As IDictionary(Of Integer, Supplier)
    Private _supplierLocationOverlay As GMapOverlay

    Public Sub New()
        InitializeComponent()
        _unitOfWork = New UnitOfWork()
        InitializeSupplierAddressMap()
        RefreshViewData()
        RefreshSupplierTable(_supplierDictionary.Values.OrderBy(Function(x) x.CompanyName))
    End Sub

    Private Sub SupplierView_FormClosed(ByVal sender As Object, ByVal e As FormClosedEventArgs) Handles Me.FormClosed
        _unitOfWork.Dispose()
    End Sub

    Private Sub InitializeSupplierAddressMap()

        GMap_SupplierAddress.MapProvider = MapProviders.GoogleMapProvider.Instance
        GMaps.Instance.Mode = AccessMode.ServerAndCache
        GMap_SupplierAddress.ForceDoubleBuffer = True
        GMap_SupplierAddress.Zoom = 8
        _supplierLocationOverlay = New GMapOverlay(GMap_SupplierAddress, "supplierLocationOverlay")
        GMap_SupplierAddress.Overlays.Add(_supplierLocationOverlay)

    End Sub

    Private Sub RefreshViewData()

        Dim supplierRepository As New Repository(Of Supplier)(_unitOfWork)
        _supplierDictionary = supplierRepository.GetAll().ToDictionary(Function(x) x.Id, Function(x) x)

    End Sub

    Private Sub RefreshSupplierTable(ByVal supplierList As IEnumerable(Of Supplier))

        dgv_Supplier.Rows.Clear()
        For Each supplier As Supplier In supplierList
            dgv_Supplier.Rows.Add(supplier.Id,
                supplier.CompanyName,
                supplier.TelephoneNumber,
                supplier.FaxNumber,
                supplier.EmailAddress)
        Next
    End Sub

    Private Sub EnsureSupplierIsSelected()
        If dgv_Supplier.SelectedRows.Count = 0 Then
            Throw New Exception("Proszę, wybierz dostawcę, aby kontynuować.")
        End If
    End Sub

    Private Function GetSelectedSupplier() As Supplier
        If dgv_Supplier.SelectedRows.Count = 0 Then
            Return Nothing
        End If
        Return _supplierDictionary(CInt(dgv_Supplier.SelectedRows(0).Cells("SupplierId").Value))
    End Function

    Private Sub dgv_Supplier_SelectionChanged(sender As System.Object, e As EventArgs) Handles dgv_Supplier.SelectionChanged
        Dim selectedSupplier As Supplier = GetSelectedSupplier()
        If Not IsNothing(selectedSupplier) Then
            lb_SupplierAddress.DataSource = selectedSupplier.SupplierAddresses
        Else
            lb_SupplierAddress.DataSource = Nothing
        End If
    End Sub

    Private Function GetSelectedSupplierAddress() As SupplierAddress
        Dim selectedSupplier As Supplier = GetSelectedSupplier()
        If Not IsNothing(selectedSupplier) Then
            Return CType(lb_SupplierAddress.SelectedValue, SupplierAddress)
        End If
        Return Nothing
    End Function

    Private Sub lb_SupplierAddress_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles lb_SupplierAddress.SelectedIndexChanged
        Dim supplierAddress As SupplierAddress = GetSelectedSupplierAddress()
        If Not IsNothing(supplierAddress) Then
            tb_SelectedSupplierAddress.Text = supplierAddress.Address.ToString()
            Dim addressLocation As New PointLatLng(supplierAddress.Address.Latitude, supplierAddress.Address.Longitude)
            Dim marker As GMapMarker = New Markers.GMapMarkerGoogleRed(addressLocation)
            _supplierLocationOverlay.Markers.Clear()
            marker.ToolTipText = supplierAddress.Supplier.CompanyName
            marker.ToolTipMode = MarkerTooltipMode.Always
            _supplierLocationOverlay.Markers.Add(marker)
            GMap_SupplierAddress.ZoomAndCenterMarkers(_supplierLocationOverlay.Id)
            GMap_SupplierAddress.Zoom = 12
        Else
            tb_SelectedSupplierAddress.Text = String.Empty
            _supplierLocationOverlay.Markers.Clear()
            GMap_SupplierAddress.ZoomAndCenterMarkers(_supplierLocationOverlay.Id)
            GMap_SupplierAddress.Zoom = 0
        End If
    End Sub


    Private Sub ts_btn_AddSupplier_Click(sender As System.Object, e As System.EventArgs) Handles ts_btn_AddSupplier.Click
        Try
            Dim supplierInputDialog As New SupplierInputDialog()
            If supplierInputDialog.ShowDialog = Windows.Forms.DialogResult.OK Then

                Dim supplier As Supplier = supplierInputDialog.Supplier
                Dim supplierRepository As New Repository(Of Supplier)(_unitOfWork)
                
                _unitOfWork.BeginTransaction()
                supplierRepository.Add(supplier)
                _unitOfWork.CommitTransaction()

                _supplierDictionary.Add(supplier.Id, supplier)
                RefreshSupplierTable(_supplierDictionary.Values.OrderBy(Function(x) x.CompanyName))

            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub ts_btn_EditSupplier_Click(sender As System.Object, e As System.EventArgs) Handles ts_btn_EditSupplier.Click
        Try
            EnsureSupplierIsSelected()
            Dim selectedSupplier As Supplier = GetSelectedSupplier()
            Dim supplierInputDialog As New SupplierInputDialog(selectedSupplier)
            If supplierInputDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then

                Dim supplierRepository As New Repository(Of Supplier)(_unitOfWork)
                _unitOfWork.BeginTransaction()
                supplierRepository.Update(supplierInputDialog.Supplier)
                _unitOfWork.CommitTransaction()

                _supplierDictionary(selectedSupplier.Id) = supplierInputDialog.Supplier
                RefreshSupplierTable(_supplierDictionary.Values.OrderBy(Function(x) x.CompanyName))

            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub ts_btn_DeleteSupplier_Click(sender As System.Object, e As System.EventArgs) Handles ts_btn_DeleteSupplier.Click
        Try
            EnsureSupplierIsSelected()
            Dim selectedSupplier As Supplier = GetSelectedSupplier()

            Dim wireOrderRepository As New Repository(Of WireOrder)(_unitOfWork)
            Dim miscellaneousOrderRepository As New Repository(Of MiscellaneousOrder)(_unitOfWork)
            Dim dieOrderRepository As New Repository(Of DieOrder)(_unitOfWork)
            Dim wireOrderSupplierSpecification As New SupplyOrders.SupplierSpecification(Of WireOrder)(selectedSupplier)
            Dim miscellaneousOrderSupplierSpecification As New SupplyOrders.SupplierSpecification(Of MiscellaneousOrder)(selectedSupplier)
            Dim dieOrderSupplierSpecification As New SupplyOrders.SupplierSpecification(Of DieOrder)(selectedSupplier)

            If wireOrderRepository.GetAllMatching(wireOrderSupplierSpecification).Any() AndAlso
               miscellaneousOrderRepository.GetAllMatching(miscellaneousOrderSupplierSpecification).Any() AndAlso
               dieOrderRepository.GetAllMatching(dieOrderSupplierSpecification).Any() Then
                Throw New Exception("Nie można usunąć dostawcy, ponieważ jest związany z zamówieniami.")
            End If

            If MessageBox.Show("Czy jesteś pewien?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then

                Dim supplierRepository As New Repository(Of Supplier)(_unitOfWork)
                _unitOfWork.BeginTransaction()
                supplierRepository.Delete(selectedSupplier)

                'wywalic niepowiazane adresy

                _unitOfWork.CommitTransaction()

                _supplierDictionary.Remove(selectedSupplier.Id)
                RefreshSupplierTable(_supplierDictionary.Values.OrderBy(Function(x) x.CompanyName))


            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub



#Region "Supplier address"

    Private Sub EnsureSupplierAddressIsSelected()
        If lb_SupplierAddress.SelectedItems.Count = 0 Then
            Throw New Exception("Proszę, wybierz adres, aby kontynuować.")
        End If
    End Sub

    Sub ts_btn_SupplierAddressAdd_Click(sender As System.Object, e As System.EventArgs) Handles ts_btn_SupplierAddressAdd.Click
        Try
            EnsureSupplierIsSelected()
            Dim addressInputDialog As New AddressInputDialog()
            If addressInputDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then

                Dim selectedSupplier As Supplier = GetSelectedSupplier()
                Dim address As Address = addressInputDialog.Address
                Dim description As String = addressInputDialog.Description

                If selectedSupplier.SupplierAddresses.Any(Function(x) x.Description = description) Then
                    Throw New ArgumentException("Dostawca posiada już adres o takim opisie.")
                End If
                selectedSupplier.AddAddres(address, description)

                Dim supplierRepository As New Repository(Of Supplier)(_unitOfWork)
                _unitOfWork.BeginTransaction()
                supplierRepository.Update(selectedSupplier)
                _unitOfWork.CommitTransaction()

                lb_SupplierAddress.DataSource = New BindingSource(selectedSupplier.SupplierAddresses, Nothing)
                MessageBox.Show("Operacja zakończona pomyślnie", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End Try
    End Sub

    Private Sub ts_btn_SupplierAddressEdit_Click(sender As System.Object, e As System.EventArgs) Handles ts_btn_SupplierAddressEdit.Click
        Try
            EnsureSupplierIsSelected()
            EnsureSupplierAddressIsSelected()
            Dim selectedSupplier As Supplier = GetSelectedSupplier()
            Dim selectedSupplierAddress As SupplierAddress = CType(lb_SupplierAddress.SelectedValue, SupplierAddress)

            Dim addressInputDialog As New AddressInputDialog(selectedSupplierAddress)
            If addressInputDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then

                If selectedSupplierAddress.Description <> addressInputDialog.Description AndAlso
                    selectedSupplier.SupplierAddresses.Any(Function(x) x.Description = addressInputDialog.Description) Then
                    Throw New ArgumentException("Dostawca posiada już adres o takim opisie.")
                End If

                selectedSupplierAddress.Description = addressInputDialog.Description
                Dim address As Address = addressInputDialog.Address
                selectedSupplierAddress.Address = addressInputDialog.Address
                Dim supplierRepository As New Repository(Of Supplier)(_unitOfWork)

                _unitOfWork.BeginTransaction()
                supplierRepository.Update(selectedSupplier)
                _unitOfWork.CommitTransaction()

                lb_SupplierAddress.DataSource = New BindingSource(selectedSupplier.SupplierAddresses, Nothing)
                MessageBox.Show("Operacja zakończona pomyślnie", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End Try
    End Sub

    Private Sub ts_btn_SupplierAddressDelete_Click(sender As System.Object, e As System.EventArgs) Handles ts_btn_SupplierAddressDelete.Click
        Try
            EnsureSupplierIsSelected()
            EnsureSupplierAddressIsSelected()
            Dim confirmationDialogResult As DialogResult = MessageBox.Show("Czy jesteś pewien?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
            If confirmationDialogResult = Windows.Forms.DialogResult.Yes Then

                Dim selectedSupplier As Supplier = GetSelectedSupplier()
                Dim selectedSupplierAddress As SupplierAddress = CType(lb_SupplierAddress.SelectedValue, SupplierAddress)

                selectedSupplier.SupplierAddresses.Remove(selectedSupplierAddress)

                Dim supplierRepository As New Repository(Of Supplier)(_unitOfWork)
                _unitOfWork.BeginTransaction()
                supplierRepository.Update(selectedSupplier)
                _unitOfWork.CommitTransaction()

                lb_SupplierAddress.DataSource = New BindingSource(selectedSupplier.SupplierAddresses, Nothing)
                MessageBox.Show("Operacja zakończona pomyślnie", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End Try
    End Sub

#End Region



End Class